var sounddb = require('../../db/sound.db')
var logger = require('../../logger')
var async = require('async')
var emit = require('../../emit')

function onsocket(socket,data){
    var user = socket.handshake.cookies.authorized;
    var filestar = data.fileid+'.star';
    async.waterfall([
        (callback) =>{
            sounddb.getfileinfo(data.fileid,(err,info) =>{
                if(err){
                    callback(err);
                }else{
                    callback(err,info);
                }
            })
        },

        //把user加到fileid.star中
        (info,callback) =>{
            sounddb.client().sadd(filestar,user,(err,response) =>{
                if(err){
                    callback(err,info);
                }else{
                    callback(null,info);
                }
            })
        },

        //统计fileid.star有多少条记录，防止同一用户对同一文件多次加星
        (info,callback) =>{
            sounddb.client().scard(filestar,(err,response) =>{
                if(err){
                    callback(err,info);
                }else{
                    callback(null,response,info);
                }
            })
        },

        //在fileinfo记录点赞数，方便查找
        (info,count,callback) =>{
            info.stars = count;
            sounddb.setfileinfo(data.fileid,info,(err) =>{
                callback(err,count);
            });
        }
    ],(err,count) =>{
        if(err){
            logger.log("error","star",err);
        }else{
            emit.send(socket,'star',{fileid:data.fileid,star:count});
        }
    });
}

module.exports = {
    onsocket
}